package org.example.domain.strategy.service.rule.tree.impl;


import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.vo.RuleLogicCheckTypeVO;
import org.example.domain.strategy.model.vo.StrategyAwardStockKeyVO;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.armory.IStrategyDispath;
import org.example.domain.strategy.service.rule.tree.ILogicTreeNode;
import org.example.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyDispath strategyDispath;
    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        log.info("规则过滤-库存扣减 userId:{} strategyId:{} awardId:{} ruleValue:{}",userId,strategyId,awardId,ruleValue);
        //扣减库存,并上锁
        Boolean status = strategyDispath.subtractionAwardStock(strategyId, awardId,endDateTime);
        //true:库存扣将并上锁成功，TAKE_OVER规则节点接管，返回奖品ID，奖品规则配置
        if(status){
            log.info("规则过滤-库存扣减-成功 userId:{} strategyId:{} awardId:{}",userId,strategyId,awardId);
            //写入延迟队列，延迟消费更新数据库记录【在trigger的job：UpdateAwardStockJob 下消费队列，更新数据库记录】
            strategyRepository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
                            .strategyId(strategyId)
                            .awardId(awardId)
                            .build());
            //TODO 按理说库存扣减成功后，就应该直接返回奖品了，没有后续的流程了，只有当库存扣减失败后才能走兜底奖励，但这里为什么要走TAKE_OVER呢
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                    .strategyAwardData(DefaultTreeFactory.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .awardRuleValue(ruleValue)
                            .build())
                    .build();
        }

        //如果库存不足，则直接返回放行
        log.warn("规则过滤-库存扣减-警告 userId:{} strategyId:{} awardId:{}",userId,strategyId,awardId);
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                .build();
    }
}
